import BaseModel from '../api/BaseModel'
import RequestResult from '../api/RequestResult'
import RequestListResult from '../api/RequestListResult'
import { BASE_URL, DEMO_URL, PAGE_SIZE } from '../api/index'
// import * as util from './index'

export let isFormal = false
const configData = {
  isFormal,
  versioncode: '',
  server: isFormal ? BASE_URL : DEMO_URL,
}
export const server = configData.server
export class RequestError {
  code = 0
  message = ""
}

export function requestList<T extends BaseModel>(
  method: 'GET' | 'POST',
  api: string,
  parameter: any,
  success: (result: RequestListResult<T>) => void,
  failure: (error: RequestError) => void,
) {
  call(method, api, parameter, success, failure)
}

export function request<T extends BaseModel>(
  method: 'GET' | 'POST',
  api: string,
  parameter: any,
  success: (result: RequestResult<T>) => void,
  failure: (error: RequestError) => void,
) {
  call(method, api, parameter, success, failure)
}

const call = (
  method: "GET" | "POST",
  api: string,
  parameter: any,
  successCallback: (result: any) => void,
  failedCallback: (result: any) => void
) => {

  let url = server + toUrl(api, parameter)
  $.ajax({
    url,
    method,
    headers: { versioncode: configData.versioncode },
  })
    .done((data: any, textStatus: any, jqXHR: any) => {
      successCallback(data)
    })
    .fail((jqXHR: any, textStatus: any, errorThrown: any) => {
      console.warn(errorThrown)
      failedCallback(textStatus)
    })
}

const toUrl = (api: string, parameter: any): string => {
  let result = api
  let keys = Object.keys(parameter)
  let i = 0
  for (let k of keys) {
    result += i == 0 ? '?' : '&'
    result += `${encodeURI(k)}=${encodeURI(parameter[k])}`
    i++
  }
  return result
}

export const requestOld = (
  method: "GET" | "POST",
  url: string,
  successCallback: (result: any) => void,
  failedCallback: (result: any) => void
) => {

  $.ajax({
    url: url,
    method: method,
    headers: { versioncode: configData.versioncode },
  })
    .done((data: any, textStatus: any, jqXHR: any) => {
      successCallback(data)
    })
    .fail((jqXHR: any, textStatus: any, errorThrown: any) => {
      console.warn(errorThrown)
      failedCallback(textStatus)
    })
}
